//
//  UITextField_runtime.swift
//  Maotai
//
//  Created by BO ZHOU on 2020/11/24.
//

import UIKit


private var textDidChangedBlock_key = "textDidChangedBlock_key"
public extension UITextField {
    
    /**
     * textfield文字实时改变监听回调
     */
    var textDidChangedBlock: ((String)->())? {
        get {
            if let a = objc_getAssociatedObject(self, &textDidChangedBlock_key) as? ((String)->())? {
                return a
            }
            return nil
        }
        set {
            
            // zwarning: OBJC_ASSOCIATION_ASSIGN 使用这个坑逼, 不能正确存储
            objc_setAssociatedObject(self, &textDidChangedBlock_key, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC)
            
//            if !self.canPerformAction(#selector(textFieldDidChange(textfield:)), withSender: self) {
//                self.addTarget(self, action: #selector(textFieldDidChange(textfield:)), for: .editingChanged)
//            }
            self.addTarget(self, action: #selector(textFieldDidChange(textfield:)), for: .editingChanged)

        }
    }
    
    @objc private func textFieldDidChange(textfield: UITextField) {

        if textfield.markedTextRange == nil {

            // 通知父控件根据textfield的关键字筛选查询
            if let text = textfield.text {
                textDidChangedBlock?(text)
            }
        }
    }
    
}
